#include <iostream>
#include <vector>
#include <string>

static const std::vector<int8_t> cipher {
#include "59.txt"
};

static int num_of_the(const char a, const char b, const char c) {
    std::string s;
    int n = (cipher.size() / 3) * 3;
    for (int i = 0; i < n; i += 3) {
        s += (cipher[i] ^ a);
        s += (cipher[i+1] ^ b);
        s += (cipher[i+2] ^ c);
    }

    std::string t {"the"};
    int r = 0;
    size_t pos = 0;
    while ((pos = s.find(t, pos)) != std::string::npos) {
        ++r;
        pos += t.size();
    }
    return r;
}

static std::string decrypt(const char a, const char b, const char c) {
    std::string s;
    int n = (cipher.size() / 3) * 3;
    for (int i = 0; i < n; i += 3) {
        s += (cipher[i] ^ a);
        s += (cipher[i+1] ^ b);
        s += (cipher[i+2] ^ c);
    }
    if (cipher.size() - n == 1) {
        s += (cipher[n] ^ a);
    } else if (cipher.size() - n == 2) {
        s += (cipher[n++] ^ a);
        s += (cipher[n++] ^ b);
    }
    return s;
}

int main() {
    int s = 0;
    int i, j, k;
    for (char a = 'a'; a <= 'z'; ++a) {
        for (char b = 'a'; b <= 'z'; ++b) {
            for (char c = 'a'; c <= 'z'; ++c) {
                int t = num_of_the(a, b, c);
                if (t > s) {
                    s = t;
                    i = a;
                    j = b;
                    k = c;
                }
            }
        }
    }
    std::cout << "Num of \"the\": " << s << std::endl;
    std::cout << "=================\n" << std::endl;
    std::string o = decrypt(i, j, k);
    std::cout << o << std::endl;
    int r = 0;
    for (auto e : o) 
        r += e;
    std::cout << r << std::endl;
}

